// 配置管理模块
// 用于保存和加载网站的爬取配置

/**
 * 根据URL生成配置键名
 * @param {string} url - 网站URL
 * @returns {string} 配置键名
 */
export const getConfigKey = (url) => {
  try {
    const urlObj = new URL(url)
    // 使用域名作为配置键，去掉协议和www前缀
    let domain = urlObj.hostname.replace(/^www\./, '')
    return `crawl_config_${domain}`
  } catch (error) {
    console.error('URL解析失败:', error)
    // 如果URL解析失败，使用URL的hash作为键
    return `crawl_config_${btoa(url).replace(/[^a-zA-Z0-9]/g, '')}`
  }
}

/**
 * 保存配置到本地存储
 * @param {string} url - 网站URL
 * @param {object} config - 配置对象
 */
export const saveConfig = async (url, config) => {
  try {
    const key = getConfigKey(url)
    const configData = {
      url: url,
      listSelector: config.listSelector || '',
      titleSelector: config.titleSelector || '',
      titleLinkSelector: config.titleLinkSelector || '',
      dateSelector: config.dateSelector || '',
      nextPageSelector: config.nextPageSelector || '',
      maxPages: config.maxPages || 3,
      customSelectors: config.customSelectors || [],
      savedAt: new Date().toISOString()
    }

    // 检查Chrome存储API是否可用
    if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
      // 使用Chrome存储API保存配置
      await chrome.storage.local.set({ [key]: configData })
      console.log('配置已保存到Chrome存储:', key, configData)
    } else {
      // 降级到localStorage
      localStorage.setItem(key, JSON.stringify(configData))
      console.log('配置已保存到localStorage:', key, configData)
    }
    return true
  } catch (error) {
    console.error('保存配置失败:', error)
    throw error
  }
}

/**
 * 从本地存储加载配置
 * @param {string} url - 网站URL
 * @returns {object|null} 配置对象或null
 */
export const loadConfig = async (url) => {
  try {
    const key = getConfigKey(url)

    // 检查Chrome存储API是否可用
    if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
      const result = await chrome.storage.local.get([key])
      if (result[key]) {
        console.log('配置已从Chrome存储加载:', key, result[key])
        return result[key]
      }
    } else {
      // 降级到localStorage
      const stored = localStorage.getItem(key)
      if (stored) {
        const config = JSON.parse(stored)
        console.log('配置已从localStorage加载:', key, config)
        return config
      }
    }

    console.log('未找到配置:', key)
    return null
  } catch (error) {
    console.error('加载配置失败:', error)
    return null
  }
}

/**
 * 删除配置
 * @param {string} url - 网站URL
 */
export const deleteConfig = async (url) => {
  try {
    const key = getConfigKey(url)

    // 检查Chrome存储API是否可用
    if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
      await chrome.storage.local.remove([key])
      console.log('配置已从Chrome存储删除:', key)
    } else {
      // 降级到localStorage
      localStorage.removeItem(key)
      console.log('配置已从localStorage删除:', key)
    }
    return true
  } catch (error) {
    console.error('删除配置失败:', error)
    throw error
  }
}

/**
 * 获取所有保存的配置
 * @returns {object} 所有配置
 */
export const getAllConfigs = async () => {
  try {
    const configs = {}

    // 检查Chrome存储API是否可用
    if (typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local) {
      const result = await chrome.storage.local.get(null)
      // 筛选出爬取配置
      Object.keys(result).forEach(key => {
        if (key.startsWith('crawl_config_')) {
          configs[key] = result[key]
        }
      })
    } else {
      // 降级到localStorage
      for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i)
        if (key && key.startsWith('crawl_config_')) {
          const stored = localStorage.getItem(key)
          if (stored) {
            configs[key] = JSON.parse(stored)
          }
        }
      }
    }

    console.log('所有配置:', configs)
    return configs
  } catch (error) {
    console.error('获取所有配置失败:', error)
    return {}
  }
}
